﻿using iS3.Server.MetaConfig.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using iS3.Server.Core.Core;

namespace iS3.Server.MetaConfig
{
    //数据模板管理类
    public class DMTManager
    {

        #region 路径
        private static string templateRootPath = AppDomain.CurrentDomain.BaseDirectory + "config";
        private static string templateSysPath = templateRootPath + "/sys/";
        private static string getTemplatePrjPath(string prj) { return templateRootPath + "/prj/"; }
        #endregion

        #region  管理内容
        private  List<DataModelTemplate> sysDataModelTemplates = new List<DataModelTemplate>();    //系统数据模板

        private  Dictionary<string, List<DataModelTemplate>> prjDataModelTemplateDict = new Dictionary<string, List<DataModelTemplate>>();  //项目数据模板字典

        #endregion
        private static DMTManager manager;

        public static DMTManager getInstance()
        {
            if (manager == null)
            {
                manager = new DMTManager();
            }
            return manager;
        }
       public void Init()
        {
            //运行开始时启动，初始化当前目录下的所有类型
            loadSysDMTs();
        }


        /**
         * 加载所有的系统数据模板
         */
         void  loadSysDMTs()
        {

            DirectoryInfo directoryInfo = new DirectoryInfo(templateSysPath);
            List<FileInfo> fileInfos = directoryInfo.GetFiles().ToList();

            Console.WriteLine("[info] load sys dmt at " + templateSysPath);
            int count = 0;
            int fail = 0;
            foreach (FileInfo fi in fileInfos)
            {
                count++;
                try
                {
                    StreamReader sr = new StreamReader(fi.FullName, Encoding.UTF8);
                    String content = sr.ReadToEnd();
                    DataModelTemplate dmt = JsonConvert.DeserializeObject<DataModelTemplate>(content);
                    sysDataModelTemplates.Add(dmt);

                    Console.WriteLine(string.Format("[info] {0}. load dmt {1}({2}) success", count, dmt.Name, dmt.Code));
                }
                catch(Exception ex)
                {
                    fail++;
                    Console.WriteLine(string.Format("[error] ---{0}. load  fail at {1}", count, fi.FullName));
                }
            }
            Console.WriteLine(string.Format("[info] load sys dmt finish! total:{0}, fail:{1}", count, fail));
        }

        /**
         * 判断该code在sys内是否存在
         */
        bool checkIfSysDMTExist(string code)
        {
            return sysDataModelTemplates.Where(x => x.Code == code).ToList().Count > 0;
        }


        public List<DataModelTemplate> getSysListSimple()
        {
            List<DataModelTemplate> result = new List<DataModelTemplate>();
            foreach (DataModelTemplate dmt in sysDataModelTemplates)
            {
                DataModelTemplate _dmt = JsonConvert.DeserializeObject<DataModelTemplate>(JsonConvert.SerializeObject(dmt));
                _dmt.PropertyMetas = new List<PropertyMate>();
                result.Add(_dmt);
            }
            return result;
        }
        /**
         * 添加模板到系统模板内
         */
        public bool add2Sys(DataModelTemplate dmt)
        {
            dmt.InheritanceRelations = null;
            dmt.Relations = null;
            string json = JsonConvert.SerializeObject(dmt);

            string dmtCode = dmt.Code;

            if (checkIfSysDMTExist(dmtCode))
            {
                //已经存在该code的对象
                throw new iS3Exception(string.Format("不能重复添加code为{0}的数据模板", dmtCode));
            }
            else
            {
                string path = templateSysPath + dmtCode + ".json";
                FileStream fs = new FileStream(path, FileMode.Create);
                StreamWriter sw = new StreamWriter(fs);
                //开始写入
                sw.Write(json);
                //清空缓冲区
                sw.Flush();
                //关闭流
                sw.Close();
                fs.Close();


                //更新到列表中
                sysDataModelTemplates.Add(dmt);

                return true;
            }
        }
    }
}
